<template>
  <basic-container>
    <div v-show="showSearchFlag" class="flex-start m-t-20 m-b-10">
      <div class="flex-center">
        <el-date-picker v-model="searchDate" class="m-r-10" end-placeholder="结束日期" range-separator="至"
                        size="small"
                        start-placeholder="开始日期"
                        type="daterange"
                        value-format="yyyy-MM-dd"
                        @change="handleDateSelect"
        />

        <el-input v-model="search.deviceName" class="m-r-10" placeholder="请输入" size="small"
                  style="width: 300px;">
          <el-button slot="append" :loading="loading" icon="el-icon-search" size="small" type="primary" @click="query">
            查询
          </el-button>
        </el-input>
      </div>
    </div>
    <div class="flex-center m-b-10">
      <div></div>
      <div class="flex-center">
        <el-button :loading="loading" circle icon="el-icon-refresh" @click="query"></el-button>
        <el-button circle icon="el-icon-search" @click="showSearchFlag=!showSearchFlag"></el-button>
        <el-button type="primary" @click="showAddFlag=true">固件升级</el-button>
      </div>
    </div>
    <el-table v-loading="loading" :data="data" :header-cell-style="{background:'#eee',color:'#000'}" border
              class="my-table"
              style="width: 100%">
      <el-table-column align="center" label="序号" type="index" width="60"/>
      <el-table-column label="产品" prop="price" min-width="100">
        <template v-slot="scope">{{ scope.row.deviceName | defaultValue }}</template>
      </el-table-column>
      <el-table-column label="分组" min-width="100">
        <template v-slot="scope">{{ scope.row.groupName | defaultValue }}</template>
      </el-table-column>
      <el-table-column label="DeviceName(主板号)" width="200">
        <template v-slot="scope">{{ scope.row.deviceName | defaultValue }}</template>
      </el-table-column>
      <el-table-column label="当前版本号" min-width="120">
        <template v-slot="scope">{{ scope.row.currentFirmwareVersion | defaultValue }}</template>
      </el-table-column>
      <el-table-column label="目标固件名称" min-width="120">
        <template v-slot="scope">{{ scope.row.firmwareName | defaultValue }}</template>
      </el-table-column>
      <el-table-column label="目标固件版本号" min-width="140">
        <template v-slot="scope">{{ scope.row.currentFirmwareVersion | defaultValue }}</template>
      </el-table-column>
      <el-table-column label="下发时间" min-width="100">
        <template v-slot="scope">{{ scope.row.startTime | defaultValue }}</template>
      </el-table-column>
      <el-table-column label="升级状态" width="200">
        <template v-slot="{row}">
          <el-button v-if="row.status === 1" size="small" type="text" @click="toRemove(row)">已下发</el-button>
          <el-button v-if="row.status === 2" size="small" type="text" @click="toRemove(row)">升级中</el-button>
          <el-button v-if="row.status === 3" size="small" type="text" @click="toRemove(row)">升级成功</el-button>
          <el-popover
            v-if="row.status === 4"
            placement="top-start"
            width="200"
            trigger="hover"
            :content="row.desc">
            <span  slot="reference">升级失败</span>
          </el-popover>
          <el-button icon="el-icon-remove" size="small" type="text" @click="toRemove(row)">删除任务</el-button>
        </template>
      </el-table-column>
    </el-table>
    <app-pagination ref="paginationRef" :page-size="page.size" :total="total" class="m-t-20" @change="pageChange"/>
    <div class="h-100px"></div>

    <el-dialog :visible.sync="showAddFlag" append-to-body title="固件升级" width="900px" destroy-on-close>
      <div class="m-b-20 flex-start">
        <span class="m-r-5" style="font-weight: 600" >目标固件</span>
        <search-firmware :show-title="false" @select="handleFirmwareSel"></search-firmware>
      </div>
      <div class="flex-start m-b-20">
        <search-product-group need-parent :parent-id="productId" class="m-r-10" title="设备组" @select="deviceQuery.groupId=$event.ids;getDevices()"/>
        <el-input v-model="deviceQuery.deviceName" class="m-r-10" placeholder="请输入" size="small"
                  style="width: 300px;">
          <el-button slot="append" :loading="loading" icon="el-icon-search" size="small" type="primary" @click="resetQuery">
            查询
          </el-button>
        </el-input>
      </div>
      <el-table v-loading="loading" :data="devices" :header-cell-style="{background:'#eee',color:'#000'}" border
                class="my-table"
                style="width: 100%"
                @select="handleSelect"
                ref="macMultipleTable"
      >
        <el-table-column type="selection" width="55">
        </el-table-column>
        <el-table-column align="center" label="序号" type="index" width="60"/>
        <el-table-column label="主板号" prop="price">
          <template v-slot="scope">{{ scope.row.productName | defaultValue }}</template>
        </el-table-column>
        <el-table-column label="产品">
          <template v-slot="scope">{{ scope.row.productName | defaultValue }}</template>
        </el-table-column>
        <el-table-column label="设备组" width="200">
          <template v-slot="scope">{{ scope.row.groupName | defaultValue }}</template>
        </el-table-column>
        <el-table-column label="当前版本号">
          <template v-slot="scope">{{ scope.row.firmwareVersion | defaultValue }}</template>
        </el-table-column>
      </el-table>
      <app-pagination  ref="paginationRef2" :page-size="deviceQuery.size" :total="deviceQuery.total" class="m-t-20" @change="pageChange2"/>
      <div class="dividing-line m-t-20 m-b-20"></div>
      <div class="flex-end">
        <el-button size="small" @click="closeAddAndEdit">取消</el-button>
        <el-button :loading="submitLoading" size="small" type="primary" @click="doConfirm">确定</el-button>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import AppPagination from "@/components/business/app-pagination";
import {
  equals,
  getRecords,
  getTotal,
  isListEmpty,
  isStringEmpty,
  msgError,
  isTrue,
  confirmWarning, msgSuccess
} from "@/util/common-util";
import AuthWrapper from "@/components/business/auth-wrapper";
import request from "@/router/axios";
import {deleteRecord} from "@/api/business/filling-team";
import SearchProduct from "@/components/SearchCondition/SearchProduct";
import SearchProductGroup from "@/components/SearchCondition/SearchProductGroup";
import AppFileUpload from "@/components/business/app-file-upload";
import {iotfirmwareupgradePage, iotfirmwareupgradeUpgrade} from "@/api/product/upgrade";
import {iotdevicePage} from "@/api/product/mainboard";
import {iotfirmwarePage} from "@/api/product/firmware";
import SearchFirmware from "@/components/SearchCondition/SearchFirmware";

export default {
  name: "UpgradeRecord",
  components: {SearchFirmware, AppFileUpload, SearchProductGroup, SearchProduct, AuthWrapper, AppPagination},
  data() {
    return {
      page: {
        size: 20,
        current: 1
      },
      page2: {
        size: 10,
        current: 1
      },
      total: 0,
      searchDate: '',
      search: {
        deviceName: '',
        startTime: '',
        endTime: '',
      },
      form: {
        id: '',
        deviceIds: ''
      },
      showSearchFlag: true,
      loading: false,
      data: [{}],
      showAddFlag: false,
      submitLoading: false,
      isEdit: false,
      selectedList: [],
      devices: [],
      deviceQuery: {
        current: 1,
        size: 10,
        total: 0,
        deviceName: '',
        groupId: ''
      },
      targetFirmware: '',
      productId: '',
    }
  },
  watch: {
    showAddFlag(val) {
      if(val) {
        this.getDevices()
      }
    }
  },
  mounted() {
    this.query()
  },
  methods: {
    handleFirmwareSel($event) {
      this.targetFirmware=$event.ids
      this.productId=$event.pid
      this.selectedList = []
      this.devices = []
      this.$refs.macMultipleTable.clearSelection()
    },
    handleSelect(arr) {
      this.$set(this,'selectedList', arr)
      console.log(this.selectedList)
      this.$nextTick(() => {
        this.$refs.macMultipleTable.clearSelection()
        this.devices.forEach(row => {
          this.selectedList.forEach(item => {
            if(item.id === row.id) {
              this.$nextTick(() => {
                this.$refs.macMultipleTable.toggleRowSelection(row, true);
              })
            }
          })
        })

      })
    },
    getDevices() {
      if(!this.deviceQuery.groupId) return;
      iotdevicePage({...this.page2,...this.deviceQuery}).then(res => {
        this.devices = getRecords(res)
        this.deviceQuery.total = getTotal(res)
      })
    },
    handleDateSelect() {
      this.search.startTime = this.searchDate && this.searchDate.length ? this.searchDate[0] + ' 00:00:00': null
      this.search.endTime = this.searchDate && this.searchDate.length ? this.searchDate[1] + ' 23:59:59' : null
    },
    pageChange2(_page) {
      this.page2 = _page
      this.getDevices()
    },
    resetQuery() {
      this.$refs.paginationRef2.reset()
      this.getDevices()
    },
    pageChange(_page) {
      this.page = _page
      this.query()
    },
    refresh() {
      this.$refs.paginationRef.reset()
    },
    query() {
      this.loading = true
      iotfirmwareupgradePage({...this.page, ...this.search}).then(res => {
        this.data = getRecords(res)
        this.total = getTotal(res)
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    addNew() {
      this.showAddFlag = true
    },
    doConfirm() {
      if (!this.targetFirmware) return msgError("请选择升级固件")
      if (!this.devices.length) return msgError("请选择升级设备")
      this.submitLoading = true
      this.form.id = this.targetFirmware
      this.form.deviceIds = this.selectedList.map(item => item.id).toString()
      iotfirmwareupgradeUpgrade(this.form).then(res => {
        this.submitLoading = false
        this.page.current = 1
        this.deviceQuery.current = 1
        this.query()
        this.closeAddAndEdit()
      }).catch(() => {
        this.submitLoading = false
      })
    },
    toDetail(row) {
      this.$emit('detail', row)
    },
    closeAddAndEdit() {
      this.showAddFlag = false
      this.form.name = ''
      this.form.contactName = ''
      this.form.contactPhone = ''
      this.form.baseUrl = ''
      this.form.authToken = ''
      this.form.id = null
      this.isEdit = false
      this.targetFirmware = null
    },
    toRemove(row) {
      confirmWarning('删除操作', `确定删除主机厂 ${row.name} ？`, () => {
        remove(row.id).then(res => {
          this.query()
          msgSuccess()
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.my-table {
  /deep/ .el-button--small {
    padding: 0 5px !important;
    font-size: 14px !important;
  }

  /deep/ td {
    padding: 8px 0 !important;
  }
}
</style>
